<template>
	<view class=""> 
		<u-navbar scrollable=false titleStyle="font-size:40rpx;color:#333;" bgColor="#f5f5f5" :placeholder='true'
			title="联系客服" :autoBack="true">
		</u-navbar>
		<view class="padding32 box fsdfsd" @click="showemo=false;isShowpicAndVideo=false">
			<view class="mb24" v-for="(item,index) in list" :key="index" :class="'Intoindex'+item.ID">
				<!-- 我的消息 -->
				<view class="flex" v-if="item.from==tencent_user_id" style="align-items:flex-start;justify-content: flex-end;">
					<view class="fontS30 bgf"
						style="padding: 20rpx 10rpx;border-radius:16rpx;background: #FFE2E5;max-width:70%;" v-if="item.type=='TIMTextElem'">
						{{item.payload.text}}
					</view>
					<image :src="item.payload.imageInfoArray[0].imageUrl" mode="widthFix"
						style="width:300rpx;border-radius: 10rpx;" v-if="item.type=='TIMImageElem'"
						@click="peivieImage(item.payload.imageInfoArray)"></image>
					<view style="width: 400rpx;height: 500rpx;overflow: hidden;" v-if="item.type=='TIMVideoFileElem' ">
						<video :src="item.payload.videoUrl" autoplay :poster='item.payload.snapshotUrl'
							v-if="videoList[index]" style="border-radius:10rpx;width: 400rpx;height: 500rpx;"
							object-fit='cover'>
						</video>
						<view class="relative" v-else @click="playvideo(index)">
							<view
								style="border-radius: 10rpx;height:500rpx ; background: rgba(0, 0, 0, 0.4);position: absolute;z-index: 9;width: 100%;">
							</view>
							<image :src="item.payload.snapshotUrl" mode="widthFix" style="width: 100%;border-radius: 10rpx;"></image>
							<view class="cof flexCenter"
								style="position: absolute;z-index: 10;top:35%;left:50%;transform: translateX(-50%) translateY(-50%);text-align: center;">
								<u-icon name="play-right-fill" size="30" color="#fff"></u-icon>
								<view class="mt24">00:00</view>
							</view>
						</view>
					</view>
					<!-- 头像 -->
					<image :src="item.avatar"
						style="width: 80rpx;height: 80rpx;background-color: #fff;border-radius: 50%;margin-left: 10rpx;">
					</image>
				</view>
				<!-- 别人的消息 -->
				<view class="flex" v-else style="align-items:flex-start;">
					<!-- 头像 -->
					<image :src="item.avatar"
						style="width: 80rpx;height: 80rpx;background-color: #fff;border-radius: 50%;">
					</image>
					<view style="margin-left: 10rpx;flex: 1;" class="flex">
						<view class="fontS30 bgf"
							style="padding: 20rpx 10rpx;border-radius:16rpx;background: #FFE2E5;max-width:70%;"
							v-if="item.type=='TIMTextElem'">
							{{item.payload.text}}
						</view>
						<image :src="item.payload.imageInfoArray[0].imageUrl" mode="widthFix"
							style="width:300rpx;border-radius: 10rpx;" v-if="item.type=='TIMImageElem'"
							@click="peivieImage(item.payload.imageInfoArray)"></image>
						<view style="width: 400rpx;height: 500rpx;overflow: hidden;" v-if="item.type=='TIMVideoFileElem' ">
							<video :src="item.payload.videoUrl" autoplay :poster='item.payload.snapshotUrl'
								v-if="videoList[index]" style="border-radius:10rpx;width: 400rpx;height: 500rpx;"
								object-fit='cover'>
							</video>
							<view class="relative" v-else @click="playvideo(index)">
								<view
									style="border-radius: 10rpx;height:500rpx ; background: rgba(0, 0, 0, 0.4);position: absolute;z-index: 9;width: 100%;">
								</view>
								<image :src="item.payload.snapshotUrl" mode="widthFix"
									style="width: 100%;border-radius: 10rpx;"></image>
								<view class="cof flexCenter"
									style="position: absolute;z-index: 10;top:35%;left:50%;transform: translateX(-50%) translateY(-50%);text-align: center;">
									<u-icon name="play-right-fill" size="30" color="#fff"></u-icon>
									<view class="mt24">00:00</view>
								</view>
							</view>
						</view>
					</view>
					
				</view>
			</view>
		</view>  
		<view class="bottomINpout  bgf fixed" style="z-index: 9999;min-height: 100rpx;">
			<view class="flexJBC padding32" style="align-items: flex-end;">
				<view style="height: 60rpx;">
					<!-- 语音 -->
					<!-- <image src="../../static/images/Frame (5).png" mode=""
						style="width: 48rpx;height: 48rpx;margin-right: 32rpx;"></image> -->
				</view>
				<u-textarea :focus="cursor" :cursorSpacing='20' :cursor="resStart" confirmType='done' 
					v-model="sendValue" placeholder="请输入内容" autoHeight height="40rpx" fixed></u-textarea>
				<view style="height:60rpx;" class="flex">
					<!-- 表情 -->
					<!-- <image src="../../static/images/Frame (6).png" mode=""
						@click="isShowpicAndVideo=false;showemo=!showemo"
						style="width: 48rpx;height: 48rpx;margin:0 32rpx;"></image> -->
					<image src="../../static/images/Frame (8).png" mode="" style="width: 48rpx;height: 48rpx;margin-left: 32rpx;"
						@click="showemo=false;isShowpicAndVideo=!isShowpicAndVideo"></image>
					<view class="fontS24"
						style="background-color:#FFE2E5;height: 60rpx;line-height: 60rpx;padding: 0 30rpx;border-radius: 15rpx;margin-left: 32rpx;"
						v-if="sendValue" @click="sendText">
						发送
					</view>
				</view>
			</view>
			<view class="padding32 flex" style="border-top: 1rpx solid #eee;" v-if='isShowpicAndVideo || showemo'>
				<!-- 表情 -->
				<view class="expression" v-if="showemo">
					<scroll-view class="emojis_scroll" :scroll-x="false" :scroll-y="true">
						<view v-for="(item,index) in emojis" :key="index" class="emoji"
							@click="ChooseToLook(`${item.emoji}`)">
							{{item.emoji}}
						</view>
					</scroll-view>
				</view>
				<!-- 上传图片或视频 -->
				<view class="flex" v-if="isShowpicAndVideo">
					<view class="center " @click="sendImag">
						<view style="background-color: #f5f5f5;padding: 10rpx;border-radius: 30rpx;">
							<u-icon name="photo" size="40"></u-icon>
						</view>
						<view class="">
							图片
						</view>
					</view>
					<view class="center " @click="sendVideo" style="margin-left: 32rpx;">
						<view style="background-color: #f5f5f5;padding: 10rpx;border-radius: 30rpx;">
							<u-icon name="rewind-right-fill" size="40"></u-icon>
						</view>
						<view class="">
							视频
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>

</template>

<script>
	import MyVideo from '@/componentes/ifram.vue'
	export default {
		components: {
			MyVideo
		},
		data() {
			return {
				videoList: [], //视频播放数组
				pageheight: 0,
				scrollTop: 0,
				tencent_user_id: '', //当前IM账号
				cursor: false, //是否聚焦
				resStart: '', //input光标位置
				emojis: [{
						emoji: '😃'
					},
					{
						emoji: '🤣'
					},
					{
						emoji: '😁'
					},
					{
						emoji: '😆'
					},
					{
						emoji: '😅'
					},
					{
						emoji: '😇'
					},
					{
						emoji: '😋'
					},
					{
						emoji: '😜'
					},
					{
						emoji: '🤭'
					},
					{
						emoji: '😖'
					},
					{
						emoji: '😣'
					},
					{
						emoji: '🤩'
					}, {
						emoji: '☺️'
					},
					{
						emoji: '🤑'
					}, {
						emoji: '🧐'
					},
					{
						emoji: '🤫'
					}, {
						emoji: '😏'
					},
					{
						emoji: '🤗'
					}, {
						emoji: '😉'
					},
					{
						emoji: '👦'
					}, {
						emoji: '👧'
					},
					{
						emoji: '💑'
					}, {
						emoji: '👨‍❤️‍👨'
					},
					{
						emoji: '🐵'
					},
				],
				showemo: false, //是否显示表情
				isShowpicAndVideo: false,
				toMessage: 'hedeqiang', //和谁发送消息
				sendValue: '', //发送的文字
				triggered: false,
				isReady: false, //系统是否已经准备好
				list: [], //对话列表
				nextReqMessageID: 0, //用于续拉，分页续拉时需传入该字段
				isCompleted: false, // 表示是否已经拉完所有消息。
				childrenId: "",
				scroll:false, //页面滚动到底部  
			}
		},
		// onLoad(option) {
		// 	this.toMessage = option.id ? option.id : 'hedeqiang'
		// },
		watch: {
			cursor(){
				// if(this.cursor){
					this.getHeight().then(res => {
						uni.pageScrollTo({ 
							scrollTop:2000 , //键盘的高度
							duration: 0, //过渡时间
						})
						console.log(this.pageheight,'fsfsdfsdfdsdfsdfsd')
					})
				// }
			},
			list() {
				this.videoList = [];
				this.list.forEach(item => {
					this.videoList.push(false)
				})
				if(this.scroll){
					console.log(this.pageheight,'fsdfsdfsd')
					this.$nextTick(()=>{
						this.getHeight().then(res => {
							uni.pageScrollTo({ 
								scrollTop: res,
								duration: 0, //过渡时间
							})
							console.log(this.pageheight,'fsfsdfsdfdsdfsdfsd')
						})
					})
					this.scroll=false
				} 
			} 
		},
		methods: {
			//点击播放视频
			playvideo(index) {
				this.$set(this.videoList, index, true)
			},
			onPageScroll(e) { //根据距离顶部距离是否显示回到顶部按钮
				this.videoList.forEach((item, index) => {
					this.$set(this.videoList, index, false)
				})
				if (e.scrollTop == 0) {
					this.scrolltoupper()
				}
			},
			// 预览图片
			peivieImage(array) {
				let imgs = []
				array.forEach(item => {
					imgs.push(item.imageUrl)
				})
				this.$my.previewImage(imgs)
			},
			// 失去焦点时获取当前光标的位置
			cursorss(event) {
				this.cursor = false; //取消聚焦
				this.resStart = event.target.cursor //保存光标位置
			},
			// 选择表情
			ChooseToLook(val) {
				let str = this.sendValue.substring(0, this.resStart) // 返回获取从0到光标位置的字符串
				this.sendValue = this.sendValue.replace(str, str + val) // 将表情插入指定位置
				this.resStart = this.resStart + 2; //光标加2(表情是占两个位置)
				console.log(this.resStart, 4545)
				this.cursor = true //设置聚焦
			},
			// 上传视频
			sendVideo() {
				let _this = this;
				uni.chooseVideo({
					count: 1,
					sourceType: ['album'], // album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
					maxDuration: 60, // 设置最长时间60s
					camera: 'back', // 后置摄像头
					success: function(res) {
						uni.showLoading({
							title: '上传中'
						})
						_this.showemo = false;
						_this.isShowpicAndVideo = false;
						let message = _this.tim.createVideoMessage({
							to: _this.toMessage,
							onlineUserOnly: true,
							conversationType: _this.TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});
						// 2. 发送消息
						let promise = _this.tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							uni.hideLoading()
							console.log(imResponse);
							_this.getList()
						}).catch(function(imError) {
							// 发送失败
							uni.hideLoading()
							_this.$my.toast('发送失败')
							console.warn('sendMessage error:', imError);
						});
					}
				})
			},
			// 上传图片
			sendImag() {
				let _this = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], // 从相册选择
					success: function(res) {
						uni.showLoading({
							title: '上传中'
						})
						_this.showemo = false;
						_this.isShowpicAndVideo = false;
						let message = _this.tim.createImageMessage({
							to: _this.toMessage,
							onlineUserOnly: true,
							conversationType: _this.TIM.TYPES.CONV_C2C,
							payload: {
								file: res
							},
							onProgress: function(event) {
								console.log('file uploading:', event)
							}
						});
						// 2. 发送消息
						let promise = _this.tim.sendMessage(message);
						promise.then(function(imResponse) {
							// 发送成功
							uni.hideLoading()
							console.log(imResponse);
							_this.getList()
						}).catch(function(imError) {
							// 发送失败
							uni.hideLoading()
							_this.$my.toast('发送失败')
							console.warn('sendMessage error:', imError);
						});
					}
				});
			},
			// 向上拉 查看历史记录
			scrolltoupper() {
				let _this = this
				uni.showLoading({
					title: '加载中'
				})
				_this.triggered = true
				console.log(12123)
				let promise = _this.tim.getMessageList({
					conversationID: 'C2C' + _this.toMessage,
					nextReqMessageID: _this.nextReqMessageID,
					count: 20
				});
				promise.then(function(imResponse) {
					setTimeout(() => {
						uni.hideLoading()
					}, 5000)
					if (!_this.isCompleted) {
						_this.list = imResponse.data.messageList.concat(_this.list); //消息列表。
						_this.list.forEach((item, index) => {
							if (index == 14) {
								let a = _this.pageheight
								setTimeout(() => {
									_this.getHeight().then(res => {
										let height = res - a
										console.log(height)
										uni.pageScrollTo({
											scrollTop: height, //滚动的距离
											duration: 0, //过渡时间
										})
										setTimeout(() => {
											uni.hideLoading()
										}, 300)
									})

								}, 100)
							}
						})
						_this.nextReqMessageID = imResponse.data.nextReqMessageID; //用于续拉，分页续拉时需传入该字段。
						_this.isCompleted = imResponse.data.isCompleted; //表示是否已经拉完所有消息。
					} else {
						// _this.$my.toast('没有更多了')
					}
					console.log(_this.list, _this.nextReqMessageID, _this.isCompleted)
				});
			},
			// 发送
			sendText() {
				let _this = this
				_this.showemo = false;
				_this.isShowpicAndVideo = false;
				if (this.isReady) {
					let message = this.tim.createTextMessage({
						to:_this.toMessage,
						conversationType: 'C2C',
						onlineUserOnly: true,
						payload: {
							text: _this.sendValue
						} 
					});
					let promise = this.tim.sendMessage(message);
					promise.then(function(imResponse) {
						// 发送成功
						_this.sendValue = '';
						_this.getList()
					}).catch(function(imError) {
						_this.$my.toast('发送失败')
						console.warn('sendMessage error:', imError); // 发送失败
					});
				} else {
					this.$my.toast('系统还没有准备好')
				}
			},
			// 消息数据
			getList(val) {
				let _this = this
				if (this.isReady) {
					let promise = _this.tim.getMessageList({
						conversationID: 'C2C' + _this.toMessage,
						count: 20
					});
					promise.then(function(imResponse) {
						_this.list = imResponse.data.messageList; //消息列表。
						if (val) {
							_this.scroll=true
						}
						// setTimeout(() => {
						// 	_this.getHeight().then(res => {
						// 		// console.log( res + (_this.isShowpicAndVideo?400:100), 'res')
						// 		uni.pageScrollTo({
						// 			scrollTop: res, //滚动的距离
						// 			duration: 0, //过渡时间
						// 		})
						// 	})
						// }, 10)
						
						_this.nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
						_this.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
					});
				} else {
					this.$my.toast('系统还没有准备好')
				}
			},
			// 获取高度
			getHeight() {
				let p = new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery()
					query.select('.fsdfsd').boundingClientRect((data) => {
						this.pageheight = data.height
						console.log(121231213, this.pageheight, 'fdsfsd')
						resolve(this.pageheight)
					}).exec()
				})
				return p

			},
		},


		// 从v2.11.2起，SDK 支持了 WebSocket，推荐接入；v2.10.2及以下版本，使用 HTTP
		onLoad(option) {
			this.toMessage = option.id ? option.id : 'hedeqiang'
			uni.showLoading({
				title: '加载中'
			})
			let _this = this
			this.tencent_user_id = uni.getStorageSync('userInfo').tencent_user_id
			// 如果没有tencent_user_id 则请求接口获取tencent_user_id
			if (!this.tencent_user_id) {
				_this.$my.post('/index/user/getImInfo').then(res => {
					if (res.code == 200) {
						_this.tencent_user_id = res.data.tencent_user_id
						// 存储 tencent_user_id 和 userSig
						let userInfo = uni.getStorageSync('userInfo')
						userInfo.tencent_user_id = res.data.tencent_user_id
						userInfo.userSig = res.data.userSig
						let promise = _this.tim.login({
							userID: res.data.tencent_user_id,
							userSig: res.data.userSig
						});
						promise.then(function(imResponse) {
							uni.hideLoading()
							console.log(imResponse.data, 'dengluchengogn'); // 登录成功
							let onSdkReady = function(event) {
								_this.isReady = true
								_this.getList(true)
							};
							_this.tim.on(_this.TIM.EVENT.SDK_READY, onSdkReady, _this); //第三个参数可以指定this对象
							if (imResponse.data.repeatLogin === true) {
								// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
							}
						}).catch(function(imError) {
							_this.$my.toast('失败')
							uni.navigateBack()
							console.warn('login error:', imError); // 登录失败的相关信息
						});
					}
				})
			} else {
				// 有账号密码
				let promise = _this.tim.login({
					userID: uni.getStorageSync('userInfo').tencent_user_id,
					userSig: uni.getStorageSync('userInfo').userSig
				});
				promise.then(function(imResponse) {
					uni.hideLoading()
					console.log(imResponse.data, 'dengluchengogn'); // 登录成功
					let onSdkReady = function(event) {
						_this.isReady = true
						_this.getList(true)
					};
					_this.tim.on(_this.TIM.EVENT.SDK_READY, onSdkReady, _this); //第三个参数可以指定this对象
					if (imResponse.data.repeatLogin === true) {
						_this.isReady = true
						_this.getList(true)
						// 标识帐号已登录，本次登录操作为重复登录。v2.5.1 起支持
					}
				}).catch(function(imError) {
					_this.$my.toast('失败')
					console.warn('login error:', imError); // 登录失败的相关信息
					uni.navigateBack()
				});
			}
			// 监听接收到的信息
			let onMessageReceived = function(event) {
				// event.data - 存储 Message 对象的数组 - [Message]
				const messageList = event.data;
				_this.getList() // 打开某个会话时，第一次拉取消息列表
			};
			_this.tim.on(_this.TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived, _this);
		},

	}
</script>

<style>
	page {
		padding-bottom: 140rpx;
	}

	.emojis_scroll {
		display: block;
		float: left;
		width: 100%;
		height: 400rpx;
		padding-left: 25rpx;
	}

	.emoji {
		display: block;
		float: left;
		width: 100rpx;
		height: 100rpx;
		font-size: 40rpx;
		text-align: center;
	}

	.bottomINpout {
		bottom: 0;
		left: 0;
		width: 100%;
	}
</style>
